package app.Cliente;

/**
 *
 * @author Pedro Santos
 */
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

public class ServerUdp extends Thread {
    /*
     * O servidor Usa a porta 8080 para escutar.
     */

    private Controller control;
    Thread thread;
    DatagramSocket socket;
    int port;
    InetAddress client; // Endereço do Cliente.
    int client_port; // Port do cliente.    

    public ServerUdp(Controller control, int port) {
        this.port = port;
        this.control = control;
    }

    @Override
    public void run() {
        try {
            byte[] buffer = new byte[1024];//Tamanho máximo da mensagem.
            int port = this.port;
            InetAddress client = null;
            int client_port = 0;
            try {
                socket = new DatagramSocket(port);
                while (true) {
                    try {
                        System.out.println("Server Iniciado!");
                        //Receive request from client
                        DatagramPacket packet =
                                new DatagramPacket(buffer, buffer.length);
                        System.out.println("Aguardando Requisição...");
                        socket.receive(packet);
                        client = packet.getAddress();
                        client_port = packet.getPort();
                        //-------Resposta---------------------
                        String capitalizedSentence = "OK";
                        byte[] sendData = capitalizedSentence.getBytes();

                        DatagramPacket sendPacket =
                                new DatagramPacket(sendData, sendData.length, client, client_port);

                        try {
                            socket.send(sendPacket);

                        } catch (IOException ex) {
                            // Logger.getLogger(Ouvinte.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        Decodificador deco = new Decodificador(control);
                        deco.decodificar(buffer, client);

                    } catch (UnknownHostException ue) {
                    }
                }
            } catch (java.net.BindException b) {
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    public void off() {
        thread.interrupted();
        socket.close();
    }

    public InetAddress getClient() {
        return client;
    }

    public void setClient(InetAddress client) {
        this.client = client;
    }

    public int getClient_port() {
        return client_port;
    }

    public void setClient_port(int client_port) {
        this.client_port = client_port;
    }
}
